// pages/coupon/buycoupon/index.js
import {
  getCouponById
} from '../../../sers/coupon/coupon';
import {
  getCouponByCode
} from '../../../sers/coupon/coupon';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    coupon: null,
    tittop: app.globalData.tittop + 'rpx',
    lbtop: app.globalData.lbtop + 'rpx',
    isWindows: app.globalData.isWindows,
    remark: '',
    isExpanded: false,
    showExpandBtn: true,
    isShowPop: false,
    isShowPopAuth: false,
    disShowPop: false,
    checked: false,
    couponInfo: '',
    myCoupon: '',
    options: '',
    hased: true,
    discunponCard: true
  },
  onReady() {
    this.checkTextOverflow();
  },



  // 定义分享内容
  onShareAppMessage() {
    return {
      title: '分享一个好物',
      path: `/pages/index/index?fromShare=1&couponId=${this.data.coupon.couponId}`, // 关键：跳转到首页，并携带参数
      // imageUrl: 'https://pic.nximg.cn/20140101/10080014_193120762000_2.jpg'
    };

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log("领券页面")
    console.log(options)
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    wx.setStorageSync('get_gif_url', currentPage.route);
    wx.setStorageSync('get_gif_status', this.data.hased);
    wx.setStorageSync('get_gif_parme', currentPage.options);
    let statusGift = wx.getStorageSync('get_gif_status')
    this.setData({
      hased: statusGift,
      options: options
    })
    this.data.options = options
    this.data.couponId = options.couponId
    getCouponByCode(this.data.options).then(coupon => {
      this.data.myCoupon = coupon.data[0]
      this.setData({
        myCoupon: coupon.data[0]
      })
      const balance = this.data.myCoupon.balance
      this.setData({
        'myCoupon.balance': Math.trunc(balance)
      })
      console.log("ioioioio")
      console.log(this.data.myCoupon)
    })
    this.getCardDis()

  },
  //判断优惠券是否被领取
  getCardDis() {
    // let giftParame = wx.getStorageSync('get_gif_parme')
    // console.log(giftParame)
    // if (this.data.options) {
    console.log(this.data.options)
    let data = {
      couponCode: this.data.options.splitIdCoupon
    }
    wx.request({
      url: app.get_request_url("checkCoupon", "coupons"),
      method: "POST",
      data: data,
      dataType: "json",
      success: res => {
        console.log(res)
        if (res.data.code == 0) {
          console.log("领取")
          console.log(res)
          if (res.data.data.status == 0) {
            this.setData({
              hased: true
            })
            // wx.showModal({
            //   title: '',
            //   content: '前往领取好友赠送券！',
            //   confirmText: '确认',
            //   cancelText: '暂不',
            //   success: (result) => {
            //     if (result.confirm) {
            //       console.log("跳转")
            //       let cunponCard = `/pages/coupon/claimCoupon/index?couponId=${giftParame.couponId}&num=${giftParame.num}&splitIdCoupon=${giftParame.splitIdCoupon}&status=${true}`
            //       wx.navigateTo({
            //         url: cunponCard
            //       });
            //     }
            //   }
            // });
          }
        } else {
          this.setData({
            hased: false
          })
          // app.showToast(res.data.msg);
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.stopPullDownRefresh();
        app.showToast("服务器请求出错");
      }
    });
    // }

  },
  //领取优惠券按钮
  submitBuyR(e) {
    // var that = this;
    var user = wx.getStorageSync("cache_shop_user_info_key") || null;
    if (user == null) {
      wx.showModal({
        title: '温馨提示',
        content: '请先登录/注册后，再领取！',
        confirmText: '确认',
        cancelText: '暂不',
        success: (result) => {
          if (result.confirm) {
            console.log("跳转")
            wx.switchTab({
              url: "/pages/usercenter/index"
            });
          }
        }
      });
    } else {
      let data = {
        mobile: user.mobile,
        couponCode: this.data.options.splitIdCoupon
      }
      wx.request({
        url: app.get_request_url("receiveSplitCoupon", "coupons"),
        method: "POST",
        data: data,
        dataType: "json",
        success: res => {
          if (res.data.code == 0) {
            wx.showToast({
              title: res.data.msg,
              duration: 1000 // 这里设置你需要的时长，单位是毫秒
            });
            this.setData({
              hased: false
            })
            setTimeout(() => {
              wx.switchTab({
                url: '/pages/coupon/index',
              });
            }, 1000);
          } else {
            app.showToast(res.data.msg);
          }
        },
        fail: () => {
          wx.hideLoading();
          wx.stopPullDownRefresh();
          app.showToast("服务器请求出错");
        }
      });
    }
  },
  // 领券获取用户是否登录
  // getuserInfo() {
  //   var user = wx.getStorageSync("cache_shop_user_info_key") || null;
  //   console.log("获取用户信息")
  //   console.log(user)
  //   if (user == null) {
  //     wx.showModal({
  //       title: '温馨提示',
  //       content: '请先登录/注册后，再领取！',
  //       confirmText: '确认',
  //       cancelText: '暂不',
  //       success: (result) => {
  //         if (result.confirm) {
  //           console.log("跳转")
  //           wx.switchTab({
  //             url: "/pages/usercenter/index"
  //           });
  //         }
  //       }
  //     });
  //   } else {
  //     let parane = {
  //       num: this.data.couponInfo.num,
  //       mobile: user.mobile,
  //       couponId: this.data.couponInfo.couponId
  //     }
  //     console.log(parane)
  //   }
  // },
  onChange(event) {
    this.setData({
      checked: event.detail,
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  toBack(e) {
    wx.navigateBack({
      delta: 1
    });
  },
})